package com.dq.service.sys.user.centre.impl;

import com.alibaba.fastjson.JSONObject;
import com.dq.controller.in.UserAccountStaffUserQuery;
import com.dq.controller.in.UserAccountStaffUserRequest;
import com.dq.domain.base.AbstractEntity;
import com.dq.domain.base.impl.BaseDaoImpl;
import com.dq.domain.orders.Orders;
import com.dq.domain.service.ServiceProject;
import com.dq.domain.subscribe.Subscribe;
import com.dq.domain.sys.user.Account;
import com.dq.domain.sys.user.UserAccount;
import com.dq.domain.sys.user.center.UserAccountStaffUser;
import com.dq.domain.sys.user.user.BossUser;
import com.dq.domain.sys.user.user.WxUser;
import com.dq.domain.sys.user.user.centre.UserCard;
import com.dq.domain.sys.user.user.centre.UserCardServiceProjectCentre;
import com.dq.exception.customException.AdminException;
import com.dq.repository.BaseRepositories;
import com.dq.service.sys.user.centre.UserAccountStaffUserService;
import com.dq.utils.RandomUtil;
import com.dq.vo.Vo;
import com.dq.vo.baseVo.VO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Author luchangtong
 * @Date 2020/4/14 15:08
 */
@Service
public class UserAccountStaffUserServiceImpl extends BaseRepositories implements UserAccountStaffUserService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Vo distributionRatio(UserAccountStaffUserRequest userAccountStaffUserRequest) throws AdminException {
        UserCard userCard = dao.get(UserCard.class,userAccountStaffUserRequest.getCardId());
        if(userCard == null){
            throw new AdminException("会员卡异常");
        }
        BigDecimal surplusPrice = BigDecimal.ZERO;
        BigDecimal surplusGivePrice = BigDecimal.ZERO;
        Account account = new Account();
        account.setUser(userCard.getWxUser());
        account.setUserCard(userCard);
        account.setSysDept(userCard.getOrg());
        account.setChangeType(userAccountStaffUserRequest.getChangeType());
        account.setOrderNo(AbstractEntity.generyStrAndMstime("Ac_"));
        account.setPayStatus(Account.PayStatus.success);
        //充值还是扣费
        if(Account.ChangeType.add.toString().equals(userAccountStaffUserRequest.getChangeType().toString())){
            BigDecimal price = userAccountStaffUserRequest.getPrice();
            if(userAccountStaffUserRequest.getDiscount() != null){
                price = price.multiply(userAccountStaffUserRequest.getDiscount().divide(new BigDecimal(100),2,RoundingMode.HALF_UP));
            }
            account.setPrice(price);
            account.setGivePrice(userAccountStaffUserRequest.getGivePrice());
            if(UserCard.CardType.one.toString().equals(userCard.getCardType().toString())){

                surplusPrice = userCard.getPrice().add(userAccountStaffUserRequest.getPrice());
                surplusGivePrice = userCard.getGivePrice().add(userAccountStaffUserRequest.getGivePrice());

                userCard.setPrice(userCard.getPrice().add(userAccountStaffUserRequest.getPrice()));
                userCard.setGivePrice(userCard.getGivePrice().add(userAccountStaffUserRequest.getGivePrice()));
            }else{
                ServiceProject serviceProject = dao.get(ServiceProject.class,userAccountStaffUserRequest.getServiceProjectId());
                if(serviceProject == null){
                    throw new AdminException("服务项目异常");
                }
                account.setServiceProject(serviceProject);
            }
            account.setStatus(Account.Status.normal);
        }else {
            BigDecimal price = userAccountStaffUserRequest.getPrice();
            if(userAccountStaffUserRequest.getDiscount() != null){
                price = price.multiply(userAccountStaffUserRequest.getDiscount().divide(new BigDecimal(100),2,RoundingMode.HALF_UP));
            }
            account.setPrice(price);
            account.setGivePrice(userAccountStaffUserRequest.getGivePrice());
            if(UserCard.CardType.one.toString().equals(userCard.getCardType().toString())){
                BigDecimal cardPrice = BigDecimal.ZERO;
                BigDecimal cardGivePrice = BigDecimal.ZERO;
                if(userCard.getPrice() != null){
                    cardPrice = userCard.getPrice();
                }
                if(userCard.getGivePrice() != null){
                    cardGivePrice = userCard.getGivePrice();
                }
                if(cardPrice.add(cardGivePrice).compareTo(price) == -1){
                    throw new AdminException("剩余余额不足");
                }
                //selected 1 正常剩余扣费 2 赠送剩余扣费
                if(userAccountStaffUserRequest.getSelected() == 1){
                    if(cardPrice.compareTo(price) == -1){
                        userCard.setGivePrice(cardGivePrice.subtract(price.subtract(cardPrice)));
                        userCard.setPrice(BigDecimal.ZERO);
                        surplusPrice = userCard.getPrice();
                        surplusGivePrice = userCard.getGivePrice();
                    }else {
                        surplusGivePrice = userCard.getGivePrice();
                        userCard.setPrice(cardPrice.subtract(price));
                        surplusPrice = userCard.getPrice();
                    }

                }else {
                    if(cardGivePrice.compareTo(price) == -1){

                        userCard.setPrice(cardPrice.subtract(price.subtract(cardGivePrice)));
                        userCard.setGivePrice(BigDecimal.ZERO);
                        surplusPrice = userCard.getPrice();
                        surplusGivePrice = userCard.getGivePrice();
                    }else {
                        surplusPrice = cardPrice;
                        userCard.setGivePrice(cardGivePrice.subtract(price));
                        surplusGivePrice = userCard.getGivePrice();
                    }
                }
            }
            //如果选择服务项目并且输入扣费金额，两者同时存在的话：判断扣费金额如果小于服务价格 在此消费记录进行特殊标识表明其扣费异常的状态
            if(userAccountStaffUserRequest.getServiceProjectId() != null && userAccountStaffUserRequest.getPrice() != null){
                ServiceProject serviceProject = dao.get(ServiceProject.class,userAccountStaffUserRequest.getServiceProjectId());
                if(serviceProject == null){
                    throw new AdminException("服务项目异常");
                }
                account.setServiceProject(serviceProject);
                if(price.compareTo(serviceProject.getProjectPrice()) == -1){
                    account.setStatus(Account.Status.abnormal);
                }else {
                    account.setStatus(Account.Status.normal);
                }
            }
        }
        account.setSurplusPrice(surplusPrice);
        account.setSurplusGivePrice(surplusGivePrice);

        account.setRechargeType(userAccountStaffUserRequest.getRechargeType());
        account.setRemarks(userAccountStaffUserRequest.getRemarks());
        account.setAccountPayType(userAccountStaffUserRequest.getAccountPayType());

        Account save = accountRepository.save(account);
        userCardRepository.save(userCard);
        if(UserCard.CardType.two.toString().equals(userCard.getCardType().toString())){
            ServiceProject serviceProject = dao.get(ServiceProject.class,userAccountStaffUserRequest.getServiceProjectId());
            if(serviceProject == null){
                throw new AdminException("服务项目异常");
            }
            UserCardServiceProjectCentre centre = userCardServiceProjectCentreRepository.findByDeletedFalseAndUserCardAndServiceProject(userCard,serviceProject);
            Long count = 0L;
            Long giveCount = 0L;
            if(centre.getCount() != null){
                count = centre.getCount();
            }
            if(centre.getGiveCount() != null){
                giveCount =centre.getGiveCount();
            }
            if(Account.ChangeType.less.toString().equals(userAccountStaffUserRequest.getChangeType().toString())){
                //selected 1 正常剩余扣费 2 赠送剩余扣费
                if(count + giveCount -1L > 0){
                    if(userAccountStaffUserRequest.getSelected() == 2){
                        if(giveCount -1L >=0){
                            centre.setGiveCount(giveCount - 1L);
                        }else {
                            centre.setCount(count - 1L);
                        }
                    }else {
                        if(centre.getCount() -1L >= 0){
                            centre.setCount(count - 1L);
                        }else {
                            centre.setGiveCount(giveCount - 1L);
                        }
                    }
                }else{
                    throw new AdminException("卡内次数不足");
                }
            }else {
                centre.setCount(count + userAccountStaffUserRequest.getNum());
                centre.setGiveCount(giveCount + userAccountStaffUserRequest.getGiveNum());
            }
            userCardServiceProjectCentreRepository.save(centre);
        }
        addUserAccountStaffUser(account,null,userAccountStaffUserRequest.getDomains(),userAccountStaffUserRequest.getChangeType(),userAccountStaffUserRequest.getRechargeType());
        WxUser wxUser = userCard.getWxUser();
        BigDecimal paytotal = BigDecimal.ZERO;
        if(wxUser.getPayTotal() != null){
            paytotal = wxUser.getPayTotal();
        }
        BigDecimal price = BigDecimal.ZERO;
        if(userAccountStaffUserRequest.getPrice() != null){
            price = userAccountStaffUserRequest.getPrice();
        }
        wxUser.setPayTotal(paytotal.add(price));
        wxUser.setPayTime(System.currentTimeMillis());
        wxUser.setTopTime(System.currentTimeMillis());
        wxUserRepository.save(wxUser);
        return new Vo(save.getId());
    }

    @Override
    public void addUserAccountStaffUser(Account account, Subscribe subscribe, List<JSONObject> domains,Account.ChangeType changeType,Account.RechargeType rechargeType) throws AdminException {
        if(domains.size() == 0){
            throw new AdminException("请填写比例");
        }
        List<UserAccountStaffUser> list = new ArrayList<>();
        Long share = 0L;
        for(JSONObject jsonObject : domains){
            System.out.println(jsonObject.get("value"));
            BossUser bossUser = dao.get(BossUser.class,Long.parseLong(jsonObject.get("value").toString()));
            UserAccountStaffUser userAccountStaffUser = new UserAccountStaffUser();
            System.out.println(jsonObject.get("discount"));
            if(jsonObject.get("discount") == null || "".equals(jsonObject.get("discount").toString())){
                throw new AdminException("请填写比例");
            }
            if(Account.RechargeType.teacher.name.equals( rechargeType.name)){
                if(Long.parseLong(jsonObject.get("discount").toString()) > 70L){
                    throw new AdminException("老师分成比例不大于70%");
                }
            }
            if(Account.RechargeType.staff.name.equals( rechargeType.name)){
                share = share+ Long.parseLong(jsonObject.get("discount").toString());
            }
            BigDecimal proportion = BigDecimal.valueOf(Long.parseLong(jsonObject.get("discount").toString()));
            BigDecimal achievements = BigDecimal.ZERO;
            proportion = proportion.divide(new BigDecimal(100),2, RoundingMode.HALF_UP);
            userAccountStaffUser.setAccount(account);
            userAccountStaffUser.setProportion(proportion);
            userAccountStaffUser.setStaffUser(bossUser);
            // add 就是充值  less 就是消耗
            if(Account.ChangeType.add.toString().equals(changeType.toString())){
                if(bossUser.getTopRatio() != null){
                    achievements = bossUser.getTopRatio().multiply(proportion.multiply(account.getPrice()));
                }
            }else {
                if(bossUser.getExpendRatio() != null){
                    achievements = bossUser.getExpendRatio().multiply(proportion.multiply(account.getPrice()));
                }
            }
            userAccountStaffUser.setAchievements(achievements);
            list.add(userAccountStaffUser);
        }
        if(share > 100L){
            throw new AdminException("员工分成比例相加不能大于100%");
        }
        if(list.size()>0){
            userAccountStaffUserRepository.saveAll(list);
        }
    }

    @Override
    public void paySubscribeUserAccountStaffUser(Account account, BossUser staffUser, BigDecimal str) {
        if(str == null){
            throw new AdminException("请填写比例");
        }
        BigDecimal proportion = str;
        proportion = proportion.divide(new BigDecimal(100),2, RoundingMode.HALF_UP);
        UserAccountStaffUser userAccountStaffUser = new UserAccountStaffUser();
        userAccountStaffUser.setAccount(account);
        userAccountStaffUser.setProportion(proportion);
        userAccountStaffUser.setStaffUser(staffUser);
        if(staffUser.getExpendRatio() == null){
            userAccountStaffUser.setAchievements(BigDecimal.ZERO);
        }else {
            userAccountStaffUser.setAchievements(staffUser.getExpendRatio().multiply(proportion.multiply(account.getPrice())));
        }
        userAccountStaffUserRepository.save(userAccountStaffUser);
    }

    @Override
    public Vo list(UserAccountStaffUserQuery userAccountStaffUserQuery) throws AdminException {
        userAccountStaffUserQuery.format();
        Map<String, Object> query = userAccountStaffUserQuery.parseMap();
        Long orgId = userAccountStaffUserQuery.getOrgId();
        if(orgId != null&&orgId!=0){
            query.put("account_sysDept_id", userAccountStaffUserQuery.getOrgId());
            query.remove("orgId");
        }
        if (orgId != null&&0==orgId) {
            query.remove("orgId");
        }
        if(userAccountStaffUserQuery.getStaffUserId() != null){
            query.put("staffUser_id",userAccountStaffUserQuery.getStaffUserId());
            query.remove("staffUserId");
        }
        if(userAccountStaffUserQuery.getUserRealcName() != null){
            query.put("staffUser_userRealcName",userAccountStaffUserQuery.getUserRealcName());
            query.remove("userRealcName");
        }
        if(userAccountStaffUserQuery.getBeginTime() != null){
            query.put("createTime"+ BaseDaoImpl.gteSqlStr,userAccountStaffUserQuery.getBeginTime());
            query.remove("beginTime");
        }
        if(userAccountStaffUserQuery.getEndTime() != null){
            query.put("createTime"+BaseDaoImpl.lteSqlStr,userAccountStaffUserQuery.getEndTime());
            query.remove("endTime");
        }

        List<UserAccountStaffUser> userAccountStaffUsers = dao.find(dao.query2Hql(UserAccountStaffUser.class,query),query);

        Long count = dao.count(dao.count2Hql(UserAccountStaffUser.class,query),query);

        PageHelper.startPage(userAccountStaffUserQuery.getPage(),userAccountStaffUserQuery.getSize());
        PageInfo pageInfo = new PageInfo((List<UserAccountStaffUser.Vo>) VO.toVOCollection(userAccountStaffUsers));
        pageInfo.setTotal(count);
        return new Vo(pageInfo);
    }

    public static void main(String[] args) {
        System.out.println(AbstractEntity.generyStrAndMstime("Ac_"));
    }
}
